package utilities;

public class HuffmanTree implements Comparable<HuffmanTree> {
	public HuffmanTree left;
	public HuffmanTree right;
	public int character;
	public double propability;
	public HuffmanTree actualSubTree;
	
	public HuffmanTree(int character, double propability) {
		this.character = character;
		this.propability = propability;
		left = null;
		right = null;
		actualSubTree = this;
	}
	
	
	
	public HuffmanTree(HuffmanTree left, HuffmanTree right) {
		this.left = left;
		this.right = right;
		this.character = -1;
		this.propability = left.propability + right.propability;
		actualSubTree = this;
	}

	public void addCode(String code, int character){
		HuffmanTree nowVisiting = this;
		for (int i=0; i<code.length(); i++){
			char c = code.charAt(i);
			if (c == '0'){
				if (nowVisiting.left == null && i == code.length()-1){
					nowVisiting.left = new HuffmanTree(character, -1.0);
				} else if (nowVisiting.left == null && i < code.length()-1){
					nowVisiting.left = new HuffmanTree(-1, -1.0);
				} else if (nowVisiting.left != null && i == code.length()-1) {
					//Kod jest zly!!!!
					System.err.println("Niepoprawny kod huffmana!!! slowo kodowe ("+code+") odpowiada dwom znakom ("+nowVisiting.left.character+" i "+character+")");
				}
				nowVisiting = nowVisiting.left;
			} else if (c == '1'){
				if (nowVisiting.right == null && i == code.length()-1){
					nowVisiting.right = new HuffmanTree(character, -1.0);
				} else if (nowVisiting.right == null && i < code.length()-1){
					nowVisiting.right = new HuffmanTree(-1, -1.0);
				} else if (nowVisiting.right != null && i == code.length()-1) {
					//Kod jest zly!!!!
					System.err.println("Niepoprawny kod huffmana!!! slowo kodowe ("+code+") odpowiada dwom znakom ("+nowVisiting.right.character+" i "+character+")");
				}
				nowVisiting = nowVisiting.right;
			}
		}
	}
	
	public Byte readValueForBit(boolean bit){
		if (bit){
			actualSubTree = actualSubTree.right;
		} else {
			actualSubTree = actualSubTree.left;
		}
		if (actualSubTree == null){
			System.err.println("Niepoprawny kod !!!");
		}
		if (actualSubTree.character != -1){
			byte ret = (byte)actualSubTree.character;
			actualSubTree = this;
			return new Byte(ret);
		}
		return null;
	}

	@Override 
	public int compareTo(HuffmanTree o) {
		if (this.propability > o.propability){
			return 1;
		} else if (this.propability < o.propability){
			return -1;
		}
		return 0;
	}
}
